import { Local } from "@/enums/Local";
/**
 * @Description: 生成一个随机token
 * @Author: Zhanghan
 * @Date: 2024-11-20 17:14:19
 */
export function generateToken(length: number) {
  const characters =
    "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
  let token = "";
  for (let i = 0; i < length; i++) {
    const randomIndex = Math.floor(Math.random() * characters.length);
    token += characters[randomIndex];
  }
  return token;
}

/**
 * @Description: 将token存储到localStorage中
 * @Author: Zhanghan
 * @Date: 2024-11-20 17:15:12
 */
export function setToken(token: string) {
  const expireTime = new Date().getTime() + 24 * 60 * 60 * 1000; // 设置当前时间加上24小时为过期时间
  const data = {
    token: token,
    expire: expireTime,
  };
  localStorage.setItem("token", JSON.stringify(data));
}

/**
 * @Description: 从localStorage中获取token
 * @Author: Zhanghan
 * @Date: 2024-11-20 17:15:42
 */
export function getToken() {
  const dataString = localStorage.getItem("token");
  if (dataString) {
    const data = JSON.parse(dataString);
    const currentTime = new Date().getTime();

    if (currentTime > data.expire) {
      // 如果过期，则删除token
      removeToken();
      return null; // token已过期，返回null
    }

    return data.token; // 返回有效的token
  }
  return null; // 如果没有token，返回null
}

/**
 * @Description: 将localStorage中的token删除
 * @Author: Zhanghan
 * @Date: 2024-11-20 17:16:02
 */
export function removeToken() {
  localStorage.removeItem("token"); // 删除token
}

/**
 * @Description: 设置本地存储
 * @Author: Zhanghan
 * @Date: 2024-12-05 14:16:45
 */
export function setLocal(key: Local, value: any) {
  localStorage.setItem(key, JSON.stringify(value));
}

/**
 * @Description: 获取本地存储
 * @Author: Zhanghan
 * @Date: 2024-12-05 14:19:02
 */
export function getLocal(key: Local) {
  const dataString = localStorage.getItem(key);
  if (dataString) {
    console.log(JSON.parse(dataString));
    
    return JSON.parse(dataString);
  } else {
    return null;
  }
}

/**
 * @Description: 清除本地存储
 * @Author: Zhanghan
 * @Date: 2024-12-05 14:19:48
 */
export function removeLocal(key: Local) {
  localStorage.removeItem(key);
}